const basicAuth = require('basic-auth')
const jwt = require('jsonwebtoken')

class Auth {
  constructor(level) {
    this.level = level || 1
    // 类变量
    Auth.USER = 8 //普通管理员
    Auth.ADMIN = 16 // 管理员
    Auth.SUPER_ADMIN = 32 // 超级管理员
  }

  get m() {
    return async (ctx, next) => {
      // HTTP 规定 身份验证机制 HttpBasicAuth
      /**
       * 获取token
       * ctx.req nodejs 原生对象
       */
      const userToken = basicAuth(ctx.req)
      let errMsg = "token不合法"
      // ctx.body = token
      console.log('----token---')
      console.log(userToken)
      if(!userToken|| !userToken.name) {
        throw new global.errs.Forbbiden(errMsg)
      }
      var decode = null
      try{
        decode = jwt.verify(userToken.name, global.config.security.secretKey)
      }catch(error){
        // 1.token不合法 2.token过期
        if(error.name == 'TokenExpiredError') {
          errMsg = 'token已过期'
        }
        throw new global.errs.Forbbiden(errMsg)
      }

       // 权限验证
      if(decode.scope < this.level) {
        errMsg = "权限不足"
        throw new global.errs.Forbbiden(errMsg)
      }

      // 拿到jwt的uid和scope
      if (decode) {
        ctx.auth = {
          uid: decode.uid,
          scope: decode.scope
        }
      }
      await next()
    }
  }

  static verifyToken(token) {
    try {
      jwt.verify(token, global.config.security.secretKey)
      return true
    } catch (error) {
      return false
    }
  }
}

module.exports = {
  Auth
}